package ru.urfc.portal.ui.client.controllers;

import ru.urfc.portal.ui.client.controllers.loaders.ConfigurableLoader;
import ru.urfc.portal.ui.client.descriptor.GridDescriptor;

import com.extjs.gxt.ui.client.data.DataProxy;
import com.extjs.gxt.ui.client.event.EventType;
import com.extjs.gxt.ui.client.event.LoadListener;

public class LoaderHandler {

	private ConfigurableLoader<?> loader;
	private RestProxy getProxy;
	private RestProxy postProxy;
	private RestProxy putProxy;
	private RestProxy deleteProxy;

	public LoaderHandler(GridDescriptor descriptor, ConfigurableLoader<?> loader) {
		this.loader = loader;
		getProxy = createProxy(descriptor, "GET");
		postProxy = createProxy(descriptor, "POST");
		putProxy = createProxy(descriptor, "PUT");
		deleteProxy = createProxy(descriptor, "DELETE");
	}

	private RestProxy createProxy(GridDescriptor descriptor, String method) {
		return RestProxy.create(descriptor.getRestUrl(method), method);
	}
	
	private void setProxyAndLoad(DataProxy<?> proxy) {
		loader.setProxy(proxy);
		loader.load();
	}

	public void loadWithGet() {
		setProxyAndLoad(getProxy);
	}

	public void loadWithPost(String requestData) {
		setProxyAndLoad(postProxy.setRequestData(requestData));
	}

	public void loadWithPut(String requestData) {
		setProxyAndLoad(putProxy.setRequestData(requestData));
	}
	
	public void loadWithDelete() {
		setProxyAndLoad(deleteProxy);
	}

	public void addListener(EventType eventType, LoadListener listener) {
		loader.addListener(eventType, listener);
	}
	
}
